/*
 * @lc app=leetcode.cn id=23 lang=cpp
 *
 * [23] 合并K个升序链表
 */
#include <vector>
using namespace std;

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    struct comp {
        bool operator()(ListNode* a, ListNode* b) {
            return a->val > b->val;
        }
    };

    //优先队列
    priority_queue<ListNode*, vector<ListNode*>, comp> q;

    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if (lists.size() == 0) return nullptr;
        ListNode* dummy = new ListNode(-1);
        ListNode* p = dummy;
        
        //将K个节点加入堆
        for (ListNode* head : lists) {
            if (head != nullptr) {
                q.push(head);
            }
        }
        while (!q.empty()) {
            ListNode* node = q.top();
            q.pop();
            p->next = node;
            if (node->next != nullptr) {
                q.push(node->next);
            }
            p = p->next;
        }
        return dummy->next;
    }
};
// @lc code=end

